﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Text;
using MySql.Data;
using MySql.Data.MySqlClient;

namespace DAOLayer
{
    using System.Windows.Forms;

    public class CDAOConfig
    {
        public  DataTable TableConfig = new DataTable();
        private MySqlDataAdapter AdapterConfig = null;
        private bool UpdatingData = false;

        /// <summary>
        /// Конструктор для объекта Конфигурации БД уровня доступа к данным
        /// </summary>
        /// <param name="Table">Таблица с данными конфигурации БД</param>
        public CDAOConfig(CDAOTransportions Transportions)
        {
            MySqlConnection Connection = Transportions.Connection;
            if (Connection == null)
            {
                throw new NoNullAllowedException("Ошибка получения конфигурации БД. Соединение не существует.");
            }
            if (Connection.State != ConnectionState.Open && !Transportions.Open())
            {
                return;
            }
            AdapterConfig = new MySqlDataAdapter("SELECT CONFIG_NAME, CONFIG_VALUE FROM config;", Connection);
            AdapterConfig.UpdateCommand = new MySqlCommand("UPDATE config SET CONFIG_VALUE=@NewValue WHERE CONFIG_NAME=@Name", Connection);
            AdapterConfig.UpdateCommand.Parameters.Add(new MySqlParameter("NewValue", MySqlDbType.VarChar, 64, "CONFIG_VALUE"));
            AdapterConfig.UpdateCommand.Parameters.Add(new MySqlParameter("Name", MySqlDbType.VarChar, 64, "CONFIG_NAME"));
            AdapterConfig.DeleteCommand = new MySqlCommand("DELETE FROM config WHERE CONFIG_NAME=@Name", Connection);
            AdapterConfig.DeleteCommand.Parameters.Add(new MySqlParameter("Name", MySqlDbType.VarChar, 64, "CONFIG_NAME"));
            AdapterConfig.InsertCommand = new MySqlCommand("INSERT INTO config (CONFIG_NAME, CONFIG_VALUE) VALUES (@Name, @NewValue)", Connection);
            AdapterConfig.InsertCommand.Parameters.Add(new MySqlParameter("NewValue", MySqlDbType.VarChar, 64, "CONFIG_VALUE"));
            AdapterConfig.InsertCommand.Parameters.Add(new MySqlParameter("Name", MySqlDbType.VarChar, 64, "CONFIG_NAME"));
            AdapterConfig.Fill(TableConfig);
            TableConfig.RowChanged += new DataRowChangeEventHandler(TableConfigRowChanged);
            TableConfig.RowDeleted += new DataRowChangeEventHandler(TableConfigRowDelete);
            TableConfig.TableNewRow += new DataTableNewRowEventHandler(TableConfigRowInsert);
        }
        /// <summary>
        /// Индексатор для доступа к различным параметрам конфигурации
        /// </summary>
        /// <param name="Name">Имя параметра</param>
        /// <returns>Возвращает значение параметра</returns>
        public string this[string Name]
        {
            get
            {
                foreach (DataRow Row in TableConfig.Rows)
                {
                    string ConfName = (string) Row["CONFIG_NAME"];
                    if (ConfName == Name)
                        return (string) Row["CONFIG_VALUE"];
                }
                return null;
            }
            set
            {
                foreach (DataRow Row in TableConfig.Rows)
                {
                    string ConfName = (string)Row["CONFIG_NAME"];
                    if (ConfName == Name)
                    {
                        Row["CONFIG_VALUE"] = value;
                        return;
                    }
                }
                throw new Exception("Параметра конфигурации с таким именем нет.");
            }
        }
        /// <summary>
        /// Метод обновляет данные настроек из базы данных
        /// </summary>
        public void Update()
        {
            UpdatingData = true;
            TableConfig.Clear();
            AdapterConfig.Fill(TableConfig);
            UpdatingData = false;
        }

        private void TableConfigRowChanged(object sender, DataRowChangeEventArgs e)
        {
            if (UpdatingData) return;
            AdapterConfig.UpdateCommand.Parameters["NewValue"].Value = e.Row["CONFIG_VALUE"];
            AdapterConfig.UpdateCommand.Parameters["Name"].Value = e.Row["CONFIG_NAME"];
            if (AdapterConfig.UpdateCommand.Connection.State == ConnectionState.Open)
                AdapterConfig.UpdateCommand.ExecuteNonQuery();
        }
        private void TableConfigRowDelete(object sender, DataRowChangeEventArgs e)
        {
            if (UpdatingData) return;
            AdapterConfig.DeleteCommand.Parameters["Name"].Value = e.Row["CONFIG_NAME"];
            if (AdapterConfig.DeleteCommand.Connection.State == ConnectionState.Open)
                AdapterConfig.DeleteCommand.ExecuteNonQuery();
        }
        private void TableConfigRowInsert(object sender, DataTableNewRowEventArgs e)
        {
            if (UpdatingData) return;
            AdapterConfig.InsertCommand.Parameters["Name"].Value = e.Row["CONFIG_NAME"];
            AdapterConfig.InsertCommand.Parameters["Value"].Value = e.Row["CONFIG_VALUE"];
            if (AdapterConfig.InsertCommand.Connection.State == ConnectionState.Open)
                AdapterConfig.InsertCommand.ExecuteNonQuery();
        }
    }
}
